<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <h1 class="centered-text">飞检考试须知</h1>
        <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
      </div>
      <div class="centered-text">
        <div class="center">
          <span class="left-span">1.飞检考试时间为75分钟,答完题可以点击“提交”,超出时间则自动交</span><br />
          <span class="left-span">卷；</span><br />

          <span class="left-span">2.考试采用100制,选择题数为6道,每题5分,填空题为6道,每题5分,简答</span><br />
          <span class="left-span">题为2题,每题20分;</span><br />

          <span class="left-span">3.每人有三次考试机会(初试一次和补考两次),考试90分及格。三次不</span><br />
          <span class="left-span">过者,当月绩效评价降低;</span><br />

          <span class="left-span">4.考试开始后不得交头接耳,翻看sop,违者不及格处理;</span><br />

          <span class="left-span">5.考试范围:2道运维技术选择题+4道运维手册选择题+6道运维手册填</span><br />
          <span class="left-span">空题+2道简答题;</span><br />

        </div>
      </div>
    </el-card>

    <el-card>
      <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName">
        <el-table-column label="#" width="50">
          <template slot-scope="scope">
            {{
              (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="科目名称" width="300">
        </el-table-column>
        <el-table-column prop="desc" label="科目详情">
        </el-table-column>
        <el-table-column prop="edit" label="操作栏" width="600">
          <template slot-scope="scope">
            <template v-if="scope.row.is_active === 1">
              <template v-if="scope.row.total_show === 0">
                <el-button v-if="scope.row.next_paper === 0" type="primary"
                  @click="startExam(scope.row.id)">开始考试</el-button>
                <el-button v-else-if="scope.row.next_paper === 1" type="info"
                  @click="startExam(scope.row.id)">补考1</el-button>
                <el-button v-else-if="scope.row.next_paper === 2" type="info"
                  @click="startExam(scope.row.id)">补考2</el-button>
                <el-button v-else type="danger">很遗憾本次考试未通过</el-button>
              </template>
              <template v-else-if="scope.row.total_show === 1">
                <el-button type="primary">恭喜通过本次考试</el-button>
              </template>
              <template v-else-if="scope.row.total_show === 2">
                <el-button type="warning">批改中</el-button>
              </template>
              <template v-else-if="scope.row.total_show === 3">
                <el-button @click="continueExam(scope.row.score_id)" type="primary">继续考试</el-button>
              </template>
            </template>
            <template v-else-if="scope.row.next_paper === 3 && scope.row.total_show === 0">
              <el-button type="danger">很遗憾本次考试未通过</el-button>
            </template>
            <template v-else-if="scope.row.total_show === 1">
              <el-button type="primary">恭喜通过本次考试</el-button>
            </template>
            <template v-else>
              <el-button type="info">考试安排中，请耐心等待</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo" :page-sizes="[5, 10, 50, 100]" :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <!-- 弹出考试框 -->
    <!-- <el-dialog :visible.sync="dialogFormVisible" :fullscreen="true" :close-on-click-modal="false" :show-close="false"
      @mousemove="resetIdleTimer" @keydown="resetIdleTimer" @click="resetIdleTimer"> -->
    <el-dialog :visible.sync="dialogFormVisible" :fullscreen="true" @mousemove="resetIdleTimer" @keydown="resetIdleTimer"
      @click="resetIdleTimer" @closed="handleDialogClosed">
      <template v-slot:title>
        <div style="text-align: center; position: fixed; width: 100%; padding: 0px; top: 0;">
          <h1>{{ examForm.title }}</h1>
          <p>考生姓名:{{ nick_name }}</p>
          <p>考试倒计时: {{ minutes }} 分 {{ seconds }} 秒</p>
          <div style="text-align: center;">
            <el-button type="info" @click="suspendExam" style="width: 150px;">暂停考试</el-button>
          </div>
        </div>
      </template>
      <el-form :model="examForm" style="margin-top: 80px;">
        <h2 v-if="examForm.other_paper_list.length > 0">选择。(共{{ examForm.other_paper_list.length }}题)</h2>
        <div v-for="(option, index) in examForm.other_paper_list">
          <!-- 单选 -->
          <div v-if="option.questionType == 'xz'">
            <h3>{{ index + 1 }}.({{ option.question_type_ch }})({{ option.score }}分){{ option.content }}</h3>
            <el-radio-group v-model="option.examinee_answer">
              <el-radio label="A">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option" @click.stop.prevent>{{ option.choice_a }}</p>
                </div>
              </el-radio><br>
              <el-radio label="B">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_b }}</p>
                </div>
              </el-radio><br>
              <el-radio label="C">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_c }}</p>
                </div>
              </el-radio><br>
              <el-radio label="D">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_d }}</p>
                </div>
              </el-radio>
            </el-radio-group>
          </div>
          <!-- 多选 -->
          <div v-else-if="option.questionType == 'mxz'">
            <h3>{{ index + 1 }}.({{ option.question_type_ch }})({{ option.score }}分){{ option.content }}</h3>
            <el-checkbox-group v-model="option.examinee_answers">
              <el-checkbox label="A">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_a }}</p>
                </div>
              </el-checkbox><br>
              <el-checkbox label="B">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_b }}</p>
                </div>
              </el-checkbox><br>
              <el-checkbox label="C">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_c }}</p>
                </div>
              </el-checkbox><br>
              <el-checkbox label="D">
                <div class="option-wrapper" @click.stop.prevent>
                  <p class="option">{{ option.choice_d }}</p>
                </div>
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>

        <!-- 判断 -->

        <div class="no-copy-paste">
          <h2 v-if="examForm.pd_paper_list.length > 0">判断。(共{{ examForm.pd_paper_list.length }}题)</h2>
          <div v-for="(option, index) in examForm.pd_paper_list">
            <!-- 判断 -->
            <div v-if="option.questionType == 'pd'">
              <h3>{{ index + 1 }}.({{ option.question_type_ch }})({{ option.score }}分){{ option.content }}</h3>
              <el-radio-group v-model="option.examinee_answer">
                <el-radio label="对">
                  <div class="option-wrapper" @click.stop.prevent>
                    <p class="option">对</p>
                  </div>
                </el-radio><br>
                <el-radio label="错">
                  <div class="option-wrapper" @click.stop.prevent>
                    <p class="option">错</p>
                  </div>
                </el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>


        <div class="no-copy-paste">
          <h2 v-if="examForm.tk_paper_list.length > 0">填空。(共{{ examForm.tk_paper_list.length }}题)</h2>
          <div v-for="(question_now, index) in examForm.tk_paper_list" :key="index" id="box1">
            <p style="display: inline-block; vertical-align: middle">
              {{ index + 1 }}.({{ "填空" }})({{ question_now.score }}分)
            </p>
            <input v-model="question_now.id" type="hidden">
            <input v-model="question_now.tk_num" type="hidden">
            <template v-for="(question, qIndex) in question_now.blanks">
              <template v-if="question.type === 'text'">
                {{ question.value }}
              </template>
              <template v-else-if="question.type === 'input'">
                <span :id="`${question_now.id}_${qIndex}`" v-if="examForm.is_staff === 0" @copy="preventCopyPaste"
                  @paste="preventCopyPaste"
                  style="width: 200px; height: 24px; line-height: 24px; font-size: 20px; padding: 1px 14px; border-bottom: 1px solid black; color: red"
                  contenteditable="true" @click="onInputClick($event)"
                  @input="handleSpanInput(question_now.id, qIndex, $event)">
                </span>
                <span :id="`${question_now.id}_${qIndex}`" v-else
                  style="width: 200px; height: 24px; line-height: 24px; font-size: 20px; padding: 1px 14px; border-bottom: 1px solid black; color: red"
                  contenteditable="true" @click="onInputClick($event)"
                  @input="handleSpanInput(question_now.id, qIndex, $event)">
                </span>
              </template>
            </template>
          </div>
        </div>
        <div class="no-copy-paste">
          <h2 v-if="examForm.jd_paper_list.length > 0">简答。(共{{ examForm.jd_paper_list.length }}题)</h2>
          <div v-for="(jd, jdIndex) in examForm.jd_paper_list" :key="jdIndex">
            <h3>{{ jdIndex + 1 }}.({{ "简答" }})({{ jd.score }}分){{ jd.content }}</h3>
            <!-- <el-input  v-model="jd.jd_examinee_answer" type="textarea" placeholder="请填写答案"></el-input> -->
            <textarea v-model="jd.jd_examinee_answer" rows="30" cols="100" v-if="examForm.is_staff === 0"
              @copy="preventCopyPaste" @paste="preventCopyPaste" style="color: red"></textarea>
            <textarea v-model="jd.jd_examinee_answer" rows="30" cols="100" v-else style="color: red"></textarea>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" style="position: fixed; bottom: 10px; width: 100%;">
        <!-- <el-button @click="dialogFormVisible = false">取 消</el-button> -->
        <div style="text-align: center;">
          <el-button type="primary" @click="submitExam" style="width: 150px;">交 卷</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import testApi from '@/api/testMange';
import { mapGetters } from 'vuex';
export default {
  methods: {
    handleDialogClosed() {
      // This method will be called when the dialog is closed
      this.getExamTitleList();
    },
    onInputClick(event) {
      event.preventDefault()
    },
    preventCopyPaste(event) {
      // 阻止复制和粘贴事件
      event.preventDefault();
      this.$message.warning('禁止复制和粘贴操作');
    },
    // handleOptionClick(option, selectedOption) {
    //   // 在这里执行赋值逻辑,selectedOption 就是选中的选项值
    //   option.examinee_answers = selectedOption;
    //   // 或者其他你需要执行的逻辑
    // },
    handleSpanInput(id, qIndex, event) {
      const inputValue = event.target.innerText;
      // 将输入值传递到后端或在需要的地方进行处理
      // 在这里你可以更新相应的数据结构或进行其他操作
      // console.log(`ID: ${id}, Question Index: ${qIndex}, Input Value: ${inputValue}`);
      // 找到对应的 tk_paper_list 对象和输入框
      const tk = this.examForm.tk_paper_list.find(tk => tk.id === id);
      if (tk) {
        const input = tk.blanks.find((blank, index) => index === qIndex && blank.type === 'input');
        if (input) {
          input.value = inputValue;
        }
      }

      // const inputValue = event.target.textContent;
      // const tkIndex = this.examForm.tk_paper_list.findIndex(tk => tk.id === id);
      // if (tkIndex !== -1) {
      //   const inputIndex = this.examForm.tk_paper_list[tkIndex].blanks.findIndex((blank, index) => index === qIndex && blank.type === 'input');
      //   if (inputIndex !== -1) {
      //     this.$set(this.examForm.tk_paper_list[tkIndex].blanks[inputIndex], 'value', inputValue);
      //   }
      // }
    },
    startCountdown() {
      this.countdownTimer = setInterval(() => {
        if (this.examForm.countdown > 0) {
          this.examForm.countdown--;
        } else if (this.examForm.countdown == -1) {

        } else {
          // 提交表单到后台
          testApi.submitFlyExam(this.examForm).then((reponse) => {
            this.examForm.tk_paper_list = []; // 清空填空题数据
            // 关闭弹窗
            this.dialogFormVisible = false;
            // 提示提交成功
            this.$message({
              message: reponse.message,
              type: "success",
            });
          });
          // 在计时结束后执行相应操作,例如关闭对话框
          this.dialogFormVisible = false;
          clearInterval(this.countdownTimer);
          // 刷新页面
          // this.getExamTitleList();
        }
      }, 1000);
    },
    continueExam(id) {
      testApi.getExamineeAnswerById(id).then((response) => {
        this.examForm = response.data;
        // // 遍历 tk_paper_list
        this.examForm.tk_paper_list.forEach(tk => {
          // console.log(tk)
          // 遍历 tk 中的 blanks
          tk.blanks.forEach((blank, index) => {
            // console.log(blank)
            // 判断 blank 的 type 是否为 'input'
            if (blank.type === 'input') {
              // console.log('set blank.value success')
              // 获取对应的 span 元素
              const spanId = `${tk.id}_${index}`;
              const spanElement = document.getElementById(spanId);

              if (spanElement) {
                // 设置 span 元素的内容
                this.$nextTick(() => {
                  spanElement.textContent = blank.value;
                });
              }
            }
          });
        });
        // this.$forceUpdate(); // 手动触发数据更新
        this.$nextTick(() => {
          this.dialogFormVisible = true
        })
        this.startIdleTimer();
      });
    },
    // continueExam(id) {
    //   // console.log("1:",this.examForm.tk_paper_list);
    //   this.setup(id);
    //   // console.log("2:",this.examForm.tk_paper_list);
    //   // this.$forceUpdate();
    // },
    // async setup(id) {
    //   try {
    //     const response = await testApi.getExamineeAnswerById(id);
    //     this.examForm = response.data;
    //     // // 遍历 tk_paper_list
    //     this.examForm.tk_paper_list.forEach(tk => {
    //       // console.log(tk)
    //       // 遍历 tk 中的 blanks
    //       tk.blanks.forEach((blank, index) => {
    //         // console.log(blank)
    //         // 判断 blank 的 type 是否为 'input'
    //         if (blank.type === 'input') {
    //           // console.log('set blank.value success')
    //           // 获取对应的 span 元素
    //           const spanId = `${tk.id}_${index}`;
    //           const spanElement = document.getElementById(spanId);

    //           if (spanElement) {
    //             // 设置 span 元素的内容
    //             this.$nextTick(() => {
    //               spanElement.textContent = blank.value;
    //             });
    //           }
    //         }
    //       });
    //     });
    //     // this.$forceUpdate(); // 手动触发数据更新
    //     this.$nextTick(() => {
    //       this.dialogFormVisible = true;
    //     })
    //     this.startIdleTimer();
    //   } catch (error) {
    //     console.error('Error fetching question by ID:', error);
    //   }
    // },
    startIdleTimer() {
      // console.log("startIdleTimer called")
      // 设置定时器
      this.timer = setTimeout(() => {
        // console.log('timer');
        this.saveExam();
      }, 40000);
    },

    resetIdleTimer() {
      // console.log('resetIdleTimer called');
      // 重置定时器
      clearTimeout(this.timer);
      // 添加条件检查，只有在弹窗显示的情况下才启动计时器
      if (this.dialogFormVisible) {
        this.startIdleTimer();
      }
    },
    saveExam() {
      this.examForm.suspend_id = 2;
      // 提交表单到后台
      testApi.submitFlyExam(this.examForm).then((response) => {
        // 清除定时器
        clearTimeout(this.timer);
        // 提示提交成功
        this.$message({
          message: "已经保存到后台，请放心作答",
          type: "success",
        });
      });
    },
    suspendExam() {
      // console.log('Suspend exam called');
      this.examForm.suspend_id = 1;
      // 提交表单到后台
      testApi.submitFlyExam(this.examForm).then((response) => {
        if (response.code !== 20000) {
          this.$message({
            message: response.message,
            type: "danger",
          });
        };
        // this.examForm.tk_paper_list = []; // 清空填空题数据 
        // 关闭弹窗
        this.dialogFormVisible = false;
        // 清除定时器
        clearTimeout(this.timer);
        // 提示提交成功
        this.$message({
          message: "已经暂停考试",
          type: "success",
        });
        // 获取更新后的考试标题列表
        this.getExamTitleList();
      });
    },
    submitExam() {
      this.examForm.suspend_id = 0;
      // console.log('Submit button clicked!');
      let isValid = true;
      // 遍历选择题目校验
      this.examForm.other_paper_list.forEach(option => {
        // console.log(option)
        if (!option.examinee_answer && (!option.examinee_answers || option.examinee_answers.length === 0)) {
          // 选项没有值  
          isValid = false;
          return false;
        }
      });
      // 遍历判断题目校验
      this.examForm.pd_paper_list.forEach(option => {
        // console.log(option)
        if (!option.examinee_answer) {
          // 选项没有值  
          isValid = false;
          return false;
        }
      });
      // 遍历填空题目进行判断
      this.examForm.tk_paper_list.forEach((tk) => {
        tk.blanks.forEach((blank) => {
          if (blank.type === 'input' && blank.value.trim() === '') {
            // 如果发现有空值，将 isValid 设置为 false
            isValid = false;
          }
        });
      });
      // 遍历简答题目校验
      this.examForm.jd_paper_list.forEach(jd => {
        if (jd.jd_examinee_answer.trim() === '') {
          // 选项没有值  
          isValid = false;
          return false;
        }
      });


      // 提交其他逻辑
      if (isValid) {
        // 通过验证
        // 提交表单到后台
        this.$confirm('确定要交卷吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户确认交卷,执行实际的交卷逻辑
          // 提交表单到后台
          testApi.submitFlyExam(this.examForm).then((reponse) => {
            this.examForm.tk_paper_list = []; // 清空填空题数据
            // 关闭弹窗
            this.dialogFormVisible = false;
            // 清除定时器
            clearTimeout(this.timer);
            // 提示提交成功
            this.$message({
              message: reponse.message,
              type: "success",
            });
            this.getExamTitleList();
          });
        }).catch(() => {
          // 用户取消交卷,不做任何操作
          this.$message({
            type: 'info',
            message: '已取消交卷'
          });
        });
      } else {
        // 失败 
        this.$message({
          message: "有题目未作答,请仔细检查！！！",
          type: "error",
        });
        console.log("error submit!!");
        return false;
      }
    },
    startExam(id) {
      testApi.startExamById(id).then((response => {
        this.examForm = response.data;
        this.dialogFormVisible = true;
        this.startIdleTimer();
      }))
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return "warning-row";
      } else if (rowIndex === 3) {
        return "success-row";
      }
      return "";
    },
    getExamTitleList() {
      testApi.getExamTitleList(this.searchModel).then((response) => {
        this.total = response.data.total;
        this.tableData = response.data.exam_title;
      });
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.getExamTitleList();
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo;
      this.getExamTitleList();
    },
  },
  created() {
    this.getExamTitleList();
  },
  computed: {
    ...mapGetters([
      // 'name',
      'is_super',
      'nick_name'
    ]),
    minutes() {
      return Math.floor(this.examForm.countdown / 60);
    },
    seconds() {
      return this.examForm.countdown % 60;
    },
  },
  mounted() {
    this.startCountdown();
    document.addEventListener('mousemove', this.resetIdleTimer);
    document.addEventListener('keydown', this.resetIdleTimer);
    document.addEventListener('click', this.resetIdleTimer)
  },
  beforeDestroy() {
    clearInterval(this.countdownTimer);
    document.removeEventListener('mousemove', this.resetIdleTimer);
    document.removeEventListener('keydown', this.resetIdleTimer);
    document.removeEventListener('click', this.resetIdleTimer);
  },
  data() {
    return {
      radioValue: '',
      countdownTimer: null,
      dialogFormVisible: false,
      timer: null,
      examForm: {
        title: "",
        countdown: 100 * 60,
        fly_exam_id: 0,
        suspend_id: 0,
        other_paper_list: [
          //   {
          //     "id": "1",
          //     "questionType": "xz",
          //     "answer": "",
          //     "content": "1",
          //     "choice_a": "A",
          //     "choice_b": "B",
          //     "choice_c": "C",
          //     "choice_d": "D",
          //   }, {
          //     "id": "2",
          //     "questionType": "mxz",
          //     "answers": ["A", "B", "C"],
          //     "content": "2",
          //     "choice_a": "A1",
          //     "choice_b": "B1",
          //     "choice_c": "C1",
          //     "choice_d": "D1",
          //   }
          // ],
          // tks: [
          //   {
          //     id: 1,
          //     tk_num: 3,
          //     blanks: [
          //       { type: "text", value: "确认故障操作对象的上联端口已关闭，先接" },
          //       { type: "input", value: "" },
          //       { type: "text", value: "，再" },
          //       { type: "input", value: "" },
          //       { type: "text", value: "（注意先后顺序）。通知NOC网络工程师上线检查热备交换机。" },
          //     ],
          //   },
          //   {
          //     id: 2,
          //     tk_num: 3,
          //     blanks: [
          //       { type: "text", value: "确认故障操作对象的上联端口已关闭，先接" },
          //       { type: "input", value: "" },
          //       { type: "text", value: "，再" },
          //       { type: "input", value: "" },
          //       { type: "text", value: "（注意先后顺序）。通知NOC网络工程师上线检查热备交换机。" },
          //     ],
          //   },
          // ],
          // jds: [
          //   {
          //     "content": "事件/故障通报时限要求和流程说明",
          //     "answer": "",
          //   }
        ],
        pd_paper_list: [],
        tk_paper_list: [
          // {
          //   id: 2,
          //   tk_num: 3,
          //   blanks: [
          //     { type: "text", value: "确认故障操作对象的上联端口已关闭，先接" },
          //     { type: "input", value: "" },
          //     { type: "text", value: "，再" },
          //     { type: "input", value: "" },
          //     { type: "text", value: "（注意先后顺序）。通知NOC网络工程师上线检查热备交换机。" },
          //   ],
          // },
        ],
        jd_paper_list: [
          // {
          //   "content": "事件/故障通报时限要求和流程说明",
          //   "jd_examinee_answer": "",
          // }
        ],
      },
      formLabelWidth: '120px',
      dialogFormVisible: false,
      title: "",
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 5,
      },
      tableData: [
        // {
        //   id: "1",
        //   subject: "杭州飞检",
        // },
        // {
        //   id: "2",
        //   subject: "贵安基础设施",
        // },
      ],
    };
  },
};
</script>

<style>
/* .el-dialog .el-input {
  width: 88%;
} */

body {
  user-select: none;
  /* 禁止用户选择文本 */
}

.no-copy-paste {
  user-select: none;
}

.centered-text {
  text-align: center;
  /* display: block; */
}

.center {
  display: inline-block;
  text-align: left;
}

.left-span {
  /* text-align: left; */
  display: block;
}

.option {
  white-space: pre-wrap;
  max-width: 1400px;
}


.option-wrapper {
  display: inline-block;
  vertical-align: top;
  margin-top: -15px;
}
</style>